<template>
	<view v-if="!loading">
		<view class="cu-form-group margin-top">
			<view class="title">选择活动</view>
			<picker @change="PickerChange" :value="pickerIndex" :range="titleList">
				<view class="picker">
					{{titleList[pickerIndex]}}
				</view>
			</picker>
		</view>
		<view class="bg-white padding" v-if="picActivities[pickerIndex].dailyAttendance">打卡次数：{{dailyAttendanceTimes}}</view>
		<view class="cu-bar bg-white margin-top">
			<view class="action">
				图片上传
			</view>
			<view class="action">
				{{imgList.length}}/2
			</view>
		</view>
		<view class="bg-white padding">
			<text class="gray">上传打卡截图</text>
		</view>
		<view class="cu-form-group padding">
			<view class="grid col-4 grid-square flex-sub">
				<view class="bg-img" v-for="(item,index) in imgList" :key="index" @tap="ViewImage" :data-url="imgList[index]">
					<image :src="imgList[index]" mode="aspectFill"></image>
					<view class="cu-tag bg-red" @tap.stop="DelImg" :data-index="index">
						<text class='cuIcon-close'></text>
					</view>
				</view>
				<view class="solids" @tap="ChooseImage" v-if="imgList.length<2">
					<text class='cuIcon-cameraadd'></text>
				</view>
			</view>
		</view>
		<!-- 提交按钮 -->
		<view class="cu-bar btn-group foot">
			<button class="cu-btn bg-blue shadow-blur round lg main-btn" @click="submit">提交</button>
		</view>
	</view>
</template>

<script>
	import utils from '@/common/utils.js'
	import upFile from '@/common/uploadUtils.js'
	import shareMsg from '@/common/shareMessage.js';
	const app = getApp();
	const db = uniCloud.database();
	const dbCmd = db.command;
	
	export default {
		data() {
			return {
				imgList: [],
				userInfo: null,
				picActivities: [],
				pickerIndex: 0,
				titleList: [],
				loading: true,
				dailyAttendanceTimes:0
			}
		},
		onShareAppMessage() {
					var pathList = getCurrentPages()
					var path = pathList[pathList.length - 1].route
					return shareMsg.shareMsg({
						title: "AIIT打卡活动",
						path: path,
						imageUrl: ""
					})
				},
		onLoad() {
			if (!app.globalData.hasLogin) {
				uni.showModal({
					title: "请先登录",
					success: (res) => {
						if (res.confirm) {
							uni.switchTab({
									url: "../profile/profile"
								})
						} else {
							uni.navigateBack({
								delta: 1
							})
						}
						
					}
				})
			} else {
				// 检查用户信息是否完整
				utils.checkUserInfo()
					.then(res => {
						this.userInfo = app.globalData.userInfo;
					})
					.catch(err => {
						uni.showModal({
							content: '请先完善个人信息',
							complete: (res) => {
								if (res.confirm) {
									uni.navigateTo({
										url: '../profile/userDetail'
									})
								} else {
									uni.navigateBack({
										delta: 1
									})
								}
							}
						})
					});
			}
			
			
			// 读取现有打卡活动
			db.collection('picActivities').where('onShow==true&&endtime>$env.now-86400000').orderBy('starttime desc, endtime asc').get().then(res => {
				this.picActivities = res.result.data;
				// 把活动标题提取出来，picker无法读取picActivities[i].picActivityTitle 数据
				var titleList = new Array();
				for (var i in this.picActivities) {
					titleList.push(this.picActivities[i].title)
				}
				this.titleList = titleList;
				this.loading = false;
			})
		},
		
		methods: {
			// 滑动选择器
			PickerChange(e) {
				this.pickerIndex = e.detail.value;
				if (this.picActivities[this.pickerIndex].daily) {
					// 打卡数据写入数据库
					db.collection('picToScores').where({
						picActivityID: this.picActivities[this.pickerIndex]._id,
						_id: this.userInfo._id,
						isApproval: true
						}).count().then(res => {
							this.dailyAttendanceTimes = res.result.total;
						})
				}
				
			},
			
			ChooseImage(e) {
				uni.chooseImage({
					count: 2, //默认9
					sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
					sourceType: ['album'], //从相册选择
					success: (res) => {
						if (this.imgList.length != 0) {
							this.imgList = this.imgList.concat(res.tempFilePaths)
						} else {
							this.imgList = res.tempFilePaths
						}
						
					}
				});
			},
			ViewImage(e) {
				uni.previewImage({
					urls: this.imgList,
					current: e.currentTarget.dataset.url
				});
			},
			DelImg(e) {
				uni.showModal({
					content: '确定要删除这张照片吗？',
					cancelText: '再看看',
					confirmText: '删除',
					success: res => {
						if (res.confirm) {
							this.imgList.splice(e.currentTarget.dataset.index, 1)
						}
					}
				})
			},
			// 提交
			submit(e) {
				var that = this;
				var timestamp = new Date().getTime();
				// 获取当天0点时间戳，如果数据库有该条记录，则说明今天已经打开，不能重复打卡
				var today_timestamp = new Date(new Date().toLocaleDateString()).getTime();
				uni.showLoading({
					title: '提交ing',
					mask: true
				})
				db.collection('picToScores').where({
					picActivityID: that.picActivities[that.pickerIndex]._id,
					uid: that.userInfo._id,
					timestamp: dbCmd.gte(today_timestamp)
				})
				.get()
				.then(res => {
					if (res.result.affectedDocs>0) {
						// 确认没有对应数据
						uni.hideLoading();
						uni.showToast({
							icon: 'none',
							title: '今日已打卡'
						})
					} else if (res.result.affectedDocs==0) {
						if (this.imgList) {
							var file_path = new Array();
							var picCloudPath = that.titleList[that.pickerIndex] + '-' + that.userInfo.name;
							upFile.mutiupload(this.imgList, file_path ,0, this.imgList.length, picCloudPath, function(file_path) {
								db.collection('picToScores')
								.add({
									uid: that.userInfo._id,
									userName: that.userInfo.name,
									timestamp: timestamp,
									picActivityID: that.picActivities[that.pickerIndex]._id,
									picActivityTitle: that.titleList[that.pickerIndex],
									imgPath: file_path,
									isApproval: false,
									dailyAttendance: that.picActivities[that.pickerIndex].dailyAttendance
								})
								.then(() => {
										uni.hideLoading();
										uni.showToast({
											title: '提交成功',
											success: () => {
												setTimeout(() => {
													uni.navigateBack({
														delta: 1
													})
												}, 1500)
											}
										})
									})
								.catch(err => {
									console.log(err)
								})
							})
						} else {
							uni.hideLoading();
							uni.showToast({
								icon: "none",
								title: '请上传照片'
							});
						}
					}
				})
			
					
				
			}
		}
	}
</script>

<style>
	.cu-bar.foot {
		position: fixed;
		width: 100%;
		bottom: 50rpx;
		z-index: 1024;
		box-shadow: 0 -1upx 6upx rgba(0, 0, 0, 0);
	}

</style>
